package org.hepeng.commons.validation.validator;

import org.hepeng.commons.util.EnumUtils;
import org.hepeng.commons.validation.constraints.EnumType;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 枚举类型值校验器
 * @author he peng
 */
public class EnumTypeValidator implements ConstraintValidator<EnumType, Object> {

    private Class<? extends Enum> enumClass;
    private String enumValueFieldName;

    @Override
    public void initialize(EnumType constraintAnnotation) {
        this.enumClass = constraintAnnotation.enumClass();
        this.enumValueFieldName = constraintAnnotation.enumValueName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (Objects.isNull(value)) {
            return true;
        }
        if (Objects.isNull(EnumUtils.valueOf(this.enumClass, this.enumValueFieldName, value))) {
            return false;
        }
        return true;
    }
}
